<template>
  <div class="order-list-container">
    <div class="page-header">
      <div class="header-title">
        <h2>订单管理</h2>
        <span class="subtitle">管理系统中的运输订单</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateOrder">
          <el-icon><Plus /></el-icon>新建订单
        </el-button>
        <el-button @click="handleImport">
          <el-icon><Upload /></el-icon>批量导入
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤区 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="订单号">
          <el-input v-model="filterForm.orderNo" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户">
          <el-select v-model="filterForm.customer" placeholder="请选择客户" clearable>
            <el-option 
              v-for="customer in customerOptions" 
              :key="customer.value" 
              :label="customer.label" 
              :value="customer.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="已确认" value="confirmed"></el-option>
            <el-option label="已分配" value="assigned"></el-option>
            <el-option label="运输中" value="intransit"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-container">
      <el-table
        v-loading="tableLoading"
        :data="orderList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>
        <el-table-column prop="customer" label="客户名称" min-width="180"></el-table-column>
        <el-table-column prop="fromAddress" label="起始地" min-width="180"></el-table-column>
        <el-table-column prop="toAddress" label="目的地" min-width="180"></el-table-column>
        <el-table-column prop="expectedPickupTime" label="预计提货时间" width="180"></el-table-column>
        <el-table-column prop="expectedDeliveryTime" label="预计送达时间" width="180"></el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope">
            ¥ {{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewOrder(scope.row)">查看</el-button>
            <el-button type="success" size="small" @click="handleApprove(scope.row)" v-if="scope.row.status === 'pending'">审核</el-button>
            <el-button type="warning" size="small" @click="handleAssign(scope.row)" v-if="scope.row.status === 'confirmed'">分配</el-button>
            <el-button type="danger" size="small" @click="handleCancel(scope.row)" v-if="['pending', 'confirmed'].includes(scope.row.status)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Download, Search, RefreshRight } from '@element-plus/icons-vue'

const router = useRouter()

// 表格加载状态
const tableLoading = ref(false)

// 选中的订单
const selectedOrders = ref([])

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 过滤表单
const filterForm = reactive({
  orderNo: '',
  customer: '',
  status: '',
  dateRange: []
})

// 客户选项
const customerOptions = [
  { value: 'customer1', label: '北京物流科技有限公司' },
  { value: 'customer2', label: '上海贸易有限公司' },
  { value: 'customer3', label: '广州电子科技有限公司' }
]

// 订单列表数据
const orderList = ref([
  {
    id: 1,
    orderNo: 'TMS-2025031401',
    customer: '北京物流科技有限公司',
    customerId: 'customer1',
    fromAddress: '北京市朝阳区建国路88号',
    toAddress: '上海市浦东新区张江高科技园区',
    expectedPickupTime: '2025-03-15 09:00:00',
    expectedDeliveryTime: '2025-03-16 18:00:00',
    status: 'pending',
    totalAmount: 5800.00,
    createTime: '2025-03-14 10:15:22',
    goods: [
      { name: '电子设备', quantity: 10, weight: 500, volume: 2 }
    ]
  },
  {
    id: 2,
    orderNo: 'TMS-2025031402',
    customer: '上海贸易有限公司',
    customerId: 'customer2',
    fromAddress: '上海市浦东新区张江高科技园区',
    toAddress: '广州市天河区珠江新城',
    expectedPickupTime: '2025-03-16 10:00:00',
    expectedDeliveryTime: '2025-03-17 20:00:00',
    status: 'confirmed',
    totalAmount: 7200.00,
    createTime: '2025-03-14 11:30:45',
    goods: [
      { name: '服装', quantity: 50, weight: 300, volume: 5 }
    ]
  },
  {
    id: 3,
    orderNo: 'TMS-2025031403',
    customer: '广州电子科技有限公司',
    customerId: 'customer3',
    fromAddress: '广州市天河区珠江新城',
    toAddress: '深圳市南山区科技园',
    expectedPickupTime: '2025-03-15 14:00:00',
    expectedDeliveryTime: '2025-03-15 18:00:00',
    status: 'intransit',
    totalAmount: 2500.00,
    createTime: '2025-03-14 09:05:10',
    goods: [
      { name: '电子元件', quantity: 1000, weight: 100, volume: 1 }
    ]
  },
  {
    id: 4,
    orderNo: 'TMS-2025031404',
    customer: '北京物流科技有限公司',
    customerId: 'customer1',
    fromAddress: '北京市海淀区中关村',
    toAddress: '天津市滨海新区',
    expectedPickupTime: '2025-03-14 16:00:00',
    expectedDeliveryTime: '2025-03-15 10:00:00',
    status: 'assigned',
    totalAmount: 3200.00,
    createTime: '2025-03-14 08:30:00',
    goods: [
      { name: '办公设备', quantity: 5, weight: 250, volume: 3 }
    ]
  },
  {
    id: 5,
    orderNo: 'TMS-2025031301',
    customer: '上海贸易有限公司',
    customerId: 'customer2',
    fromAddress: '上海市黄浦区外滩',
    toAddress: '杭州市西湖区',
    expectedPickupTime: '2025-03-13 09:00:00',
    expectedDeliveryTime: '2025-03-13 18:00:00',
    status: 'completed',
    totalAmount: 4500.00,
    createTime: '2025-03-13 07:45:30',
    goods: [
      { name: '食品', quantity: 200, weight: 400, volume: 4 }
    ]
  }
])

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    'pending': 'info',
    'confirmed': 'primary',
    'assigned': 'warning',
    'intransit': 'success',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusMap = {
    'pending': '待审核',
    'confirmed': '已确认',
    'assigned': '已分配',
    'intransit': '运输中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 处理搜索
const handleSearch = () => {
  // 实际应用中应该调用API进行搜索
  tableLoading.value = true
  setTimeout(() => {
    tableLoading.value = false
    pagination.currentPage = 1
    ElMessage.success('搜索完成')
  }, 500)
}

// 重置过滤条件
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 处理创建订单
const handleCreateOrder = () => {
  router.push('/order/create')
}

// 处理查看订单
const handleViewOrder = (row) => {
  router.push(`/order/detail/${row.id}`)
}

// 处理审核订单
const handleApprove = (row) => {
  ElMessageBox.confirm(
    `确定要审核通过订单 "${row.orderNo}" 吗？`,
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API更新订单状态
    const index = orderList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      orderList.value[index].status = 'confirmed'
      ElMessage.success('订单审核通过')
    }
  }).catch(() => {
    // 取消审核
  })
}

// 处理分配订单
const handleAssign = (row) => {
  router.push(`/order/assign/${row.id}`)
}

// 处理取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm(
    `确定要取消订单 "${row.orderNo}" 吗？`,
    '取消确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API更新订单状态
    const index = orderList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      orderList.value[index].status = 'cancelled'
      ElMessage.success('订单已取消')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 处理导入
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 处理导出
const handleExport = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要导出的订单')
    return
  }
  
  ElMessage.success(`已选择 ${selectedOrders.value.length} 个订单进行导出`)
  // 实际应用中应该调用API导出数据
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  // 重新加载数据
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  // 重新加载数据
}

onMounted(() => {
  // 实际应用中应该调用API加载数据
  tableLoading.value = true
  setTimeout(() => {
    pagination.total = orderList.value.length
    tableLoading.value = false
  }, 500)
})
</script>

<style scoped>
.order-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
